<?php

namespace App\Http\Requests\Backend\Administrator;

use Illuminate\Support\Facades\Hash;
use App\Http\Requests\Backend\BaseRequest;

class AdministratorRequest extends BaseRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'name' => 'bail|required|max:24',
            'mobile' => 'required|regex:/^1[345789][0-9]{9}$/|unique:administrators,mobile',
            'password' => 'bail|required|min:6|max:16'
        ];
        if ($this->isMethod('PUT')) {
            $rules['mobile'] = 'required|regex:/^1[345789][0-9]{9}$/|unique:administrators,mobile,'. $this->post('id');//修改时，手机号唯一性忽略用户本身
            unset($rules['password']);//修改时，密码非必填
        }

        return $rules;
    }

    public function messages()
    {
        return [
            'name.required' => '请输入姓名',
            'name.max' => '姓名长度不能超过24个字符',
            'mobile.required' => '请输入手机号',
            'mobile.regex' => '手机号格式错误',
            'mobile.unique' => '手机号已经存在',
            'password.required' => '请输入密码',
            'password.min' => '密码长度不能小于6个字符',
            'password.max' => '密码长度不能超过16个字符',
        ];
    }

    /**
     * @return array
     */
    public function filldata()
    {
        $data = [
            'name' => $this->input('name'),
            'is_ban_login' => (int)$this->input('is_ban_login'),
            'mobile' => $this->input('mobile'),
        ];

        // 编辑
        $this->input('password') && $data['password'] = Hash::make($this->input('password'));

        return $data;
    }
}
